from django.conf import settings

import json

from django.db import transaction
from django.db.models import Q
from django.core.cache import cache
from django.core.paginator import Paginator

from django.http import JsonResponse

from django.core.cache import cache
from django.http import JsonResponse, HttpResponse

from django.shortcuts import render

from focus_on_rent.utils.views import LoginRequiredMixin
from homes.models import House, Area
from users.models import User
# Create your views here.
from django.views import View

from focus_on_rent.settings import dev
from focus_on_rent.libs.qiniuyun.qiniuyun.qiniu_storage import storage
from homes.models import Area, House, Facility
from focus_on_rent.settings import dev
from homes.models import House, Area, HouseImage
from orders.models import Order
from users.models import User


class CityAreaView(View):
    # 城区列表
    def get(self, request):
        # 判断是否有缓存
        area_list = cache.get('area_list')
        if not area_list:
            try:
                areas = Area.objects.all()
                # 创建空字典
                area_list = []
                for area in areas:
                    area_list.append({
                        'aid': area.id,
                        'aname': area.name
                    })
                # 添加缓存
                cache.set('area_list', area_list)
            except Exception as e:

                return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})

        return JsonResponse({'errmsg': 'ok', 'errno': 0, 'data': area_list})


class HousesView(LoginRequiredMixin,View):
    def post(self, request):
        # 1、获取用户
        user = request.user
        # 2、获取数据
        dict = json.loads(request.body.decode())
        title = dict.get('title')
        price = dict.get('price')
        area_id = dict.get('area_id')
        address = dict.get('address')
        room_count = dict.get('room_count')
        acreage = dict.get('acreage')
        unit = dict.get('unit')
        capacity = dict.get('capacity')
        beds = dict.get('beds')
        deposit = dict.get('deposit')
        min_days = dict.get('min_days')
        max_days = dict.get('max_days')


        if not all([title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days,
                    max_days]):
            return JsonResponse({"errno": 4103, "errmsg": "参数错误"})

        try:
            price = int(float(price) * 100)
            deposit = int(float(deposit) * 100)
        except Exception as e:

            return JsonResponse({"errno": 4103, "errmsg": "参数错误"})

        try:
            area = Area.objects.get(id=area_id)
        except Exception as e:

            return JsonResponse({"errno": 4002, "errmsg": "地址不存在"})

        with transaction.atomic():
            save_id = transaction.savepoint()
            # 设置数据到模型
            house = House()
            house.user = user
            house.area = area
            house.title = title
            house.price = price
            house.address = address
            house.room_count = room_count
            house.acreage = acreage
            house.unit = unit
            house.capacity = capacity
            house.beds = beds
            house.deposit = deposit
            house.min_days = min_days
            house.max_days = max_days

            try:
                house.save()
            except Exception as e:

                transaction.savepoint_rollback(save_id)
                return JsonResponse({"errno": 4001, "errmsg": "数据库保存失败"})

            try:
                # 设置设施信息
                facility_ids = dict.get('facility')
                if facility_ids:
                    facilities = Facility.objects.filter(id__in=facility_ids)
                    for facility in facilities:
                        house.facility.add(facility)
            except Exception as e:

                transaction.savepoint_rollback(save_id)
                return JsonResponse({"errno": 4001, "errmsg": "数据库保存失败"})

            transaction.savepoint_commit(save_id)
        return JsonResponse({"errno": 0, "errmsg": "发布成功", "data": {'house_id': house.id}})

    def get(self, request):

        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p', 1)
        user = request.user

        try:
            area = Area.objects.get(id=aid)

        except Exception as e:
            return JsonResponse({'errno': 4004, 'errmsg': 'DATAERR'})
        if sk == 'booking':

            try:
                house = House.objects.filter(area_id=aid).order_by('order_count')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})
        elif sk == 'price-inc':
            try:
                house = House.objects.filter(area_id=aid).order_by('price')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})
        elif sk == 'price-des':
            try:
                house = House.objects.filter(area_id=aid).order_by('-price')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})
        else:
            try:
                house = House.objects.filter(area_id=aid).order_by('-create_time')
            except Exception as e:
                return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})
        paginator = Paginator(house, 3)
        try:
            # 获取每页商品数据
            page_houses = paginator.page(p)
        except Exception as e:
            return JsonResponse({'errno': 4004, 'errmsg': 'DATAERR'})
        # 获取列表总页数
        total_page = paginator.num_pages

        houses = []
        for h in house:
            houses.append({
                'address': h.address,
                'area_name': area.name,
                'ctime': h.create_time,
                'house_id': h.id,
                'image_url': h.index_image_url,
                'order_count': h.order_count,
                'price': h.price,
                'room_count': h.room_count,
                'title': h.title,
                'user_avatar': dev.QINIU_URL + str(h.user.avatar)
            })
        dict = {'houses': houses, 'total_page': total_page}
        return JsonResponse({'errno': 0, 'errmsg': 'OK', 'data': dict})


class HouseDetailView(View):

    def post(self, request, house_id):

        house_image = request.FILES.get('house_image')

        if not house_image:
            return JsonResponse({'errno': 4000, 'errmsg': 'NODATA'})

        try:

            house = House.objects.get(id=house_id)

        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})

        house_image=house_image.read()
        key=storage(house_image)
        try:
            house.index_image_url=key
            house.save()
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})
        try:

            h = HouseImage()
            h.house = house
            h.url = key
            h.save()
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': 'DBERR'})
        return JsonResponse({'errno': 0, 'errmsg': 'OK', 'data': {'url': dev.QINIU_URL+key}})




class MyHouses(View):

    def get(self, request):
        user = request.user
        user_id = user.id

        if user.is_authenticated:
            try:
                user = User.objects.filter(id=user_id)
            except Exception as e:
                return JsonResponse({'code': 4001,
                                     'errmsg': '用户信息错误'})

            for use in user:
                username_avatar = dev.QINIU_URL + str(use.avatar)

            try:
                houses = House.objects.filter(user_id=user_id)
            except Exception as e:
                return JsonResponse({'code': 4002,
                                     'errmsg': '没有房屋数据'})
            house_list = []
            for house in houses:
                house_list.append({

                    'address': house.address,
                    'area_name': house.area_id,
                    'ctime': house.create_time,
                    'house_id': house.id,
                    'img_url': dev.QINIU_URL + house.index_image_url,
                    'order_count': house.order_count,
                    'price': house.price,
                    'room_count': house.room_count,
                    'title': house.title,
                    'user_avatar': username_avatar

                })
            data_house = {}
            data_house['houses'] = house_list
            return JsonResponse({'data': data_house,
                                 'errmsg': 'ok',
                                 'errno': 0})


class MainPageHouse(View):

    def get(self, request):
        try:
            obj_houses = House.objects.all().order_by('-order_count')[:5]

        except Exception as e:
            return JsonResponse({'code': 4001,
                                 'errmsg': '查询房源信息错误'})
        show_list = []

        for house in obj_houses:
            show_list.append({
                'house_id': house.id,
                'img_url': dev.QINIU_URL + house.index_image_url,
                'title': house.title
            })

        return JsonResponse({'data': show_list,
                             'errmsg': 'ok',
                             'errno': 0})


class InfoForHouse(View):

    def get(self, request, house_id):

        id_of_house = house_id
        user = request.user
        log_user_id = user.id
        try:
            house = House.objects.get(id=id_of_house)
        except Exception as e:
            return JsonResponse({'code': 4001,
                                 'errmsg': '查询房源信息错误'})
        try:
            order = Order.objects.filter(house_id=id_of_house)
        except Exception as e:
            return JsonResponse({'code': 4001,
                                 'errmsg': '查询评论信息错误'})

        if user.is_authenticated:

            house.comments = []

            for orv in order:
                user_comment_id = orv.user_id
                user_comment = User.objects.filter(id=user_comment_id)
                for user_c in user_comment:
                    comment_name = user_c.username
                    house.comments.append({
                        'comments': orv.comment,
                        'ctime': orv.create_time,
                        'user_name': comment_name
                    })

            house.facilities = []

            house.hid = house.id

            house.img_urls = []

            try:
                house_pic = HouseImage.objects.filter(house_id=id_of_house)
            except Exception as e:
                return JsonResponse({'code': 4001,
                                     'errmsg': '查询房源图片信息错误'})

            for house_p in house_pic:
                house_image_url = house_p.url
                final_image_url = dev.QINIU_URL + str(house_image_url)
                house.img_urls.append(final_image_url)

            owner_id = house.user_id
            owner = User.objects.get(id=owner_id)
            house.user_avatar = dev.QINIU_URL + str(owner.avatar)
            house.user_id = owner.id
            house.user_name = owner.username

            house_dict = {}
            house_final = house.__dict__
            del house_final['_state']
            house_dict['house'] = house_final
            house_dict['user_id'] = log_user_id

        else:

            house.comments = []

            for orv in order:
                user_comment_id = orv.user_id
                user_comment = User.objects.filter(id=user_comment_id)
                for user_c in user_comment:
                    comment_name = user_c.username
                    house.comments.append({
                        'comments': orv.comment,
                        'ctime': orv.create_time,
                        'user_name': comment_name
                    })

            house.facilities = []

            house.hid = house.id

            house.img_urls = []

            try:
                house_pic = HouseImage.objects.filter(house_id=id_of_house)
            except Exception as e:
                return JsonResponse({'code': 4001,
                                     'errmsg': '查询房源图片信息错误'})

            for house_p in house_pic:
                house_image_url = house_p.url
                final_image_url = dev.QINIU_URL + str(house_image_url)
                house.img_urls.append(final_image_url)

            owner_id = house.user_id
            owner = User.objects.get(id=owner_id)
            house.user_avatar = dev.QINIU_URL + str(owner.avatar)
            house.user_id = owner.id
            house.user_name = owner.username

            house_dict = {}
            house_final = house.__dict__

            del house_final['_state']
            house_dict['house'] = house_final
            house_dict['user_id'] = -1

        return JsonResponse({'data': house_dict,
                             'errmsg': 'ok',
                             'errno': 0})
